from django.db import models
from datetime import datetime, timedelta
from django.dispatch import receiver
from django.db.models.signals import post_save


# 创建类并创建数据库表
class Guest(models.Model):
    name = models.CharField(max_length=200, verbose_name="客户名")
    age = models.IntegerField(default=20, verbose_name="年龄")
    phone = models.CharField(max_length=10, verbose_name="电话")

    def __str__(self):
        return self.name


class Hotel(models.Model):
    name = models.CharField(max_length=200, verbose_name="酒店名")
    phone = models.CharField(max_length=10, verbose_name="电话")
    city = models.CharField(max_length=200, verbose_name="城市")

    def __str__(self):
        return self.name


class Room(models.Model):
    room_no = models.IntegerField(default=101, verbose_name="房间号")
    hotel = models.ForeignKey(Hotel, null=True, on_delete=models.CASCADE, verbose_name="酒店")
    room_type = models.CharField(max_length=200, default='standard', verbose_name="房间类型")
    rate = models.FloatField(verbose_name="价格")
    is_available = models.BooleanField(default=True, verbose_name="是否可用")
    no_of_beds = models.IntegerField(default=3, verbose_name="床数量")

    def __str__(self):
        return str(self.room_no)

    def hotel_name(self):
        return self.hotel.name


class Booking(models.Model):
    room = models.ForeignKey(Room, on_delete=models.CASCADE, verbose_name="房间")
    guest = models.ForeignKey(Guest, on_delete=models.CASCADE, verbose_name="客户")
    hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, verbose_name="酒店")
    checkin_date = models.DateTimeField(default=datetime.now(), verbose_name="入住时间")
    checkout_date = models.DateTimeField(default=datetime.now() + timedelta(days=1), verbose_name="退房时间")
    check_out = models.BooleanField(default=False, verbose_name="是否退房")
    no_of_guests = models.IntegerField(default=1, verbose_name="人数")

    def __str__(self):
        return self.guest.name

    def charge(self):
        if self.check_out:
            if self.checkin_date == self.checkout_date:
                return self.room.rate
            else:
                time_delta = self.checkout_date - self.checkin_date
                total_time = time_delta.days
                total_cost = total_time * self.room.rate
                return total_cost
        else:
            return '暂未退房，退房后计算费用'


@receiver(post_save, sender=Booking)
def RType(sender, instance, created, **kwargs):
    room = instance.room
    if created:
        room.is_available = False
    room.save()
    if instance.check_out:
        room.is_available = True
    room.save()
